<script setup lang="tsx">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useRouter, useRoute } from 'vue-router'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import {
  pageVerifyRecordApi,
  adminPageVerifyRecordApi,
  exportVerifyRecordApi,
  adminExportVerifyRecordApi
} from '@/api/Activity'
import { businessListApi, merchantListApi } from '@/api/merchantManagement'
import { useUserStore } from '@/store/modules/user'
import { formatTime } from '@/utils'
const userStore = useUserStore()

const { t } = useI18n()
const { go, push } = useRouter()
const { query } = useRoute()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const api = userStore.userInfo.roles.includes('商家')
      ? adminPageVerifyRecordApi
      : pageVerifyRecordApi
    const res = await api({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      activeId: unref(query.id as any),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'subOrderNo',
    label: '子订单编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'goodsName',
    label: '核销商品',
    search: {
      componentProps: {
        placeholder: '请输入核销商品'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'goodsPrice',
    label: '商品价格',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'merchantId',
    label: '核销商户',
    search: {
      hidden: userStore.userInfo.roles.includes('商家'),
      component: 'Select',
      optionApi: async () => getMerchantList()
    },
    form: {
      hidden: true
    },
    table: {
      hidden: userStore.userInfo.roles.includes('商家'),
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.merchantShortName}</div>
              <div>ID:{row.merchantId}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'keyword',
    label: '核销用户',
    search: {
      componentProps: {
        placeholder: '请输入用户昵称/手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.nickName}</div>
              <div>{row.mobile}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'verifyTime',
    label: '核销时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const getBusinessList = async () => {
  const res = await businessListApi({
    pageNum: 1,
    pageSize: 9999
  })
  return res.data.list?.map((v) => ({
    label: v.businessShortName,
    value: v.id
  }))
}
const getMerchantList = async () => {
  const res = await merchantListApi({
    pageNum: 1,
    pageSize: 9999
  })
  return res.data.list?.map((v) => ({
    label: v.merchantShortName,
    value: v.id
  }))
}
const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { verifyTime, ...rest } = params
  let startVerifyTime, endVerifyTime
  if (verifyTime && verifyTime.length > 0) {
    startVerifyTime = verifyTime[0]
    endVerifyTime = verifyTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startVerifyTime,
    endVerifyTime,
    ...rest
  }
  getList()
}
const handleDownload = async (params: any) => {
  const { verifyTime, ...rest } = params
  let startVerifyTime, endVerifyTime
  if (verifyTime && verifyTime.length > 0) {
    startVerifyTime = verifyTime[0]
    endVerifyTime = verifyTime[1]
  }
  const currentDate = new Date()
  const time = formatTime(currentDate, 'yyyyMMddHHmmss')
  const num = Math.floor(Math.random() * 900000) + 100000
  const downloadApi = userStore.userInfo.roles.includes('商家')
    ? adminExportVerifyRecordApi
    : exportVerifyRecordApi
  const res = await downloadApi({
    startVerifyTime,
    endVerifyTime,
    activeId: unref(query.id as any),
    ...rest
  })
  const correctMimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  const url = window.URL.createObjectURL(new Blob([res.data], { type: correctMimeType }))
  let link = document.createElement('a')
  link.href = url
  link.download = `核销记录${time}${num}`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentDetailWrap class="flex-[3] ml-20px" title="核销记录">
      <template #header>
        <ElButton @click="go(-1)">
          {{ t('common.back') }}
        </ElButton>
      </template>
      <Search
        :schema="allSchemas.searchSchema"
        :show-download="true"
        @download="handleDownload"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentDetailWrap>
  </div>
</template>
